class Solution
{
public:
    int minDominoRotations(vector<int> &tops, vector<int> &bottoms)
    {
        int target1 = tops[0];
        int target2 = bottoms[0];
        int rotation1upper = 0;
        int rotation1lower = 0;
        int rotation2upper = 0;
        int rotation2lower = 0;
        int n = tops.size();
        for (int i = 1; i < n; ++i)
        {
            if (rotation1upper != -1)
            {
                if (tops[i] != target1)
                {
                    if (bottoms[i] == target1)
                    {
                        ++rotation1upper;
                        ++rotation1lower;
                    }
                    else
                    {
                        rotation1upper = -1;
                    }
                }
                else if (bottoms[i] == target1)
                {
                    ++rotation1upper;
                }
            }
            if (rotation2upper != -1)
            {
                if (bottoms[i] != target2)
                {
                    if (tops[i] == target2)
                    {
                        ++rotation2upper;
                        ++rotation2lower;
                    }
                    else
                    {
                        rotation2upper = -1;
                    }
                }
                else if (tops[i] == target2)
                {
                    ++rotation2upper;
                }
            }
        }
        int minRotation = -1;
        if (rotation1upper != -1)
        {
            minRotation = min(rotation1upper, n - rotation1upper);
            minRotation = min(minRotation, rotation1lower);
            minRotation = min(minRotation, n - rotation1lower);
        }
        if (rotation2upper != -1)
        {
            rotation2upper = min(rotation2upper, n - rotation2upper);
            rotation2lower = min(rotation2lower, n - rotation2lower);
            int rotation2 = min(rotation2upper, rotation2lower);
            if (minRotation == -1)
            {
                minRotation = rotation2;
            }
            else
            {
                minRotation = min(minRotation, rotation2);
            }
        }
        return minRotation;
    }
};